<template>
  <div class="indent-outbound-outing">
    <!-- 搜索表单 -->
    <div class="search-wrap mt5">
      <SearchForm ref="searchFormRef" :list="[...formList]" @submit="search" @reset="reset"></SearchForm>
    </div>

    <!-- 表头 -->
    <el-row class="table-head">
      <el-col :span="6" class="col1">
        <div class="mr10">
          <el-checkbox @change="setCheckAll" v-model="checkAll" :indeterminate="isIndeterminate"></el-checkbox>
        </div>
        <span>商品信息</span>
      </el-col>
      <el-col :span="3"> 商品类目</el-col>
      <el-col :span="3"> 关联客户</el-col>
      <el-col :span="2"> 商品单位</el-col>
      <el-col :span="2"> 入库时间</el-col>
      <el-col :span="2"> 可出库数量</el-col>
      <el-col :span="2"> 可出库件数</el-col>
      <el-col :span="2"> 订单编码</el-col>
      <el-col :span="2"> 仓库</el-col>
    </el-row>

    <!-- 列表 -->
    <div class="table-list">
      <el-empty description="暂无数据" v-if="!list.length" />
      <el-checkbox-group v-model="checkedList" @change="checked">
        <div class="goods" v-for="(item, index) in list" :key="index">
          <el-row>
            <el-col :span="6" class="col1">
              <!-- <el-checkbox class="mr10" :value="item.warehouseProductsId" style="width: 14px" /> -->
              <el-checkbox class="mr10" :value="item" style="width: 14px" />
              <div class="prod-info">
                <div class="left">
                  <img :src="item.mainPicUrl" alt="" />
                </div>
                <div class="right">
                  <h3 class="name">{{ item.productAliasName || "-" }}</h3>
                  <p style="white-space: break-spaces; word-break: break-all">
                    <!-- {{ getSpes(item.skuSpecification) }} -->
                    {{ item.skuSpecification }}
                  </p>
                  <p>SKU编码：{{ item.skuCode || "-" }}</p>
                  <p>ID：{{ item.productId || "-" }}</p>
                </div>
              </div>
            </el-col>
            <el-col :span="3"> {{ item.categoryNameList?.join(">") || "-" }}</el-col>
            <el-col :span="3"> {{ item.customerName + "-" + item.customerMobileCode || "-" }}</el-col>
            <el-col :span="2"> {{ getName(item.productUnit) || "-" }}</el-col>
            <el-col :span="2">{{ item.newInTime || "-" }}</el-col>
            <el-col :span="2"> {{ item.canDeliveryNum || "-" }}</el-col>
            <el-col :span="2"> {{ item.canDeliveryPartNum || "-" }}</el-col>
            <el-col :span="2" style="word-break: break-all"> {{ item.orderNo || "-" }}</el-col>
            <el-col :span="2"> {{ item.warehouseName || "-" }}</el-col>
          </el-row>
          <!-- <div class="remark">
            <div class="label">
              <span>备注：</span>
            </div>
            <el-input v-model="item.remark" placeholder="请输入"></el-input>
          </div> -->
        </div>
      </el-checkbox-group>
    </div>
    <!-- 分页 -->
    <div class="pt20 pb20" v-if="list.length > 0" style="display: flex; justify-content: flex-end">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 操作栏 -->
    <div class="action-wrap">
      <p>请选择需要出库的商品</p>
      <el-button type="primary" :disabled="checkedList.length <= 0" @click="tempSave"> 创建出库单</el-button>
    </div>

    <!-- 确认选中的checkedList会清空 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenClear"
      :message="'您正在重新选择出库仓，当前商品信息将被重置，重新添加商品，请问是否继续当前操作？'"
      :submitBtnText="'继续前往'"
      @submit="returnSubmitClear"
    />
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from "vue";
import SearchForm from "@/components/SearchForm";
import { getBusinessList } from "@/apis/manage";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";
import useCodeArrStore from "@/store/modules/select";
import { ListPage } from "@/apis/procure/warehouse";
import { getcategoryList2 } from "@/apis/products/specifications";
import { orderWaitDeliveryPage, saveTempDeliveryProduct } from "@/apis/procure/indent-outbound";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

const router = useRouter();

const formList = ref([
  {
    label: "合同编码",
    model: "orderNo",
    type: "input",
    labelWidth: "70"
  },
  {
    label: "出库仓",
    model: "warehouseId",
    type: "select",
    labelWidth: "70",
    data: [],
    props: { label: "warehouseName", value: "warehouseId" },
    required: true
  },
  {
    label: "客户信息",
    model: "associateCustomerQueryType-associateCustomer",
    type: "select-input",
    labelWidth: "80",
    data: [
      // {
      //   value: 0,
      //   label: "全部"
      // },
      {
        value: 1,
        label: "姓名"
      },
      {
        value: 2,
        label: "电话"
      }
    ],
    required: false
  },
  {
    label: "商品分类",
    model: "categoryIdList",
    type: "cascader",
    labelWidth: "70",
    data: [],
    props: { checkStrictly: false, expandTrigger: "hover", label: "name", value: "categoryId", multiple: true }
  }
]);
const formData = ref({});
const list = ref([]);
const checkedList = ref([]); //选中的数据
const isIndeterminate = ref(false);
const checkAll = ref(false);
const pagination = ref({
  page: 1,
  size: 10,
  total: 0
});
const _isOpenClear = ref(false);
const houseList = ref([]);

onMounted(async () => {
  const res = await ListPage({ page: 1, size: 9999 }); //仓库list
  houseList.value = res.data.records;
  const res2 = await getcategoryList2({ searchkey: "" }); //商品分类
  formList.value.map(item => {
    if (item.model === "warehouseId") {
      item.data = res.data.records;
    } else if (item.model === "categoryIdList") {
      item.data = res2.data;
    }
  });
});

//暂存选中的数据
const tempSave = () => {
  // console.log("选中的数据条数===", checkedList.value);

  let flag = true;
  checkedList.value.map((item, index) => {
    const next = checkedList.value[index - 1];
    if (next) {
      if (
        !(
          item.customerName + "-" + item.customerMobileCode === next.customerName + "-" + next.customerMobileCode &&
          item.warehouseName === next.warehouseName
        )
      ) {
        flag = false;
      }
    }
  });
  if (flag) {
    const wareHouseObj = houseList.value.find(item => item.warehouseId === formData.value.warehouseId);
    const warehouseId = formData.value.warehouseId;
    const warehouseName = wareHouseObj ? wareHouseObj.warehouseName : "";
    const _time = new Date().getTime();

    saveTempDeliveryProduct({
      code: _time,
      productInfoDTOList: checkedList.value
    }).then(res => {
      if (res.code === 200) {
        router.push({
          path: "/procure/indent-outbound/put",
          query: { _time: _time, warehouseId: warehouseId, warehouseName: warehouseName }
        });
      }
    });
  } else {
    ElMessage({
      message: "只能选择同一个仓库、同一个关联客户的商品",
      type: "error"
    });
  }
};

const getName = code => {
  return useCodeArrStore().getDictName("shop_unit", code);
};

const getList = async () => {
  console.log("表单数据===", formData.value);
  const res = await orderWaitDeliveryPage({
    ...formData.value,
    categoryIdList: formData.value?.categoryIdList ? formData.value.categoryIdList.map(item => item[item.length - 1]) : [],
    page: pagination.value.page,
    size: pagination.value.size
  });
  list.value = res.data.records;
  pagination.value.total = res.data.total;
};

//清空选中项的询问弹窗submit回调
const returnSubmitClear = () => {
  _isOpenClear.value = false; //关闭清空选中项的询问弹窗
  nextTick(() => {
    resetChecked();
    getList();
  });
};

// 表单查询组件submit回调
const search = form => {
  if (form) {
    let _form = JSON.parse(JSON.stringify(form));
    formData.value = _form;
    // console.log("处理后的数据", formData.value);
  } else {
    formData.value = {};
  }
  if (checkedList.value.length > 0) {
    _isOpenClear.value = true; //打开清空选中项的询问弹窗
  } else {
    nextTick(() => {
      resetChecked();
      getList();
    });
  }
};

//清空查询表单
const reset = () => {
  list.value = [];
  resetChecked();
  // search("");
};

/**
 * 选中
 */
const checked = value => {
  const arr = [];
  const Arr = value.map(item => item.warehouseProductsId);
  list.value.map(item => {
    if (Arr.includes(item.warehouseProductsId)) {
      arr.push(item.warehouseProductsId);
    }
  });
  const checkedCount = arr.length;
  checkAll.value = checkedCount !== 0 && checkedCount === list.value.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < list.value.length;
};
/**
 * 设置全选
 */
const setCheckAll = val => {
  const arr = []; //筛选出的非当前页选中项
  if (!val) {
    // 取消全选
    list.value.map(item => {
      const index = checkedList.value.findIndex(item2 => item2.warehouseProductsId === item.warehouseProductsId);
      if (index >= 0) {
        checkedList.value.splice(index, 1);
      }
    });
  } else {
    // 全选
    checkedList.value.map(item => {
      const currPids = list.value.map(item2 => item2.warehouseProductsId);
      if (!currPids.includes(item.warehouseProductsId)) {
        arr.push(item);
      }
    });
  }
  // console.log(arr);

  checkedList.value = val ? [...arr, ...list.value] : [...checkedList.value];
  isIndeterminate.value = false;
};

const reviewCheck = () => {
  const arr = [];
  const Arr = checkedList.value.map(item => item.warehouseProductsId);
  list.value.map(item => {
    if (Arr.includes(item.warehouseProductsId)) {
      arr.push(item);
    }
  });
  // console.log(1111111, arr);
  checked(arr);
};

const resetChecked = () => {
  checkedList.value = [];
  checkAll.value = false;
  isIndeterminate.value = false;
};

const handleSizeChange = async val => {
  pagination.value.size = val;
  await getList();
  reviewCheck();
};
const handleCurrentChange = async val => {
  pagination.value.page = val;
  await getList();
  reviewCheck();
};
//拼接商品的sku规格
const getSpes = properties => {
  if (!properties) return "-";
  const arr = JSON.parse(properties) || [];
  if (arr.length > 1) {
    const str = arr.reduce((a, b) => {
      return a.specificationVal + "+" + b.specificationVal;
    });
    return str;
  } else if (arr.length === 1) {
    return arr[0].specificationVal;
  } else {
    return "-";
  }
};
</script>

<style lang="scss" scoped>
.indent-outbound-outing {
  padding-bottom: 64px;

  .search-wrap {
    background-color: #f6f8fa;
    padding: 20px;
  }

  .col1 {
    display: flex;
    align-items: center;
    justify-content: flex-start !important;

    .prod-info {
      display: flex;

      .left {
        img {
          width: 80px;
          height: 80px;
          border-radius: 4px;
        }
      }

      .right {
        padding-left: 18px;

        .name {
          font-size: 14px;
          color: #3d3d3d;
          margin-bottom: 5px;
        }

        p {
          font-size: 12px;
          color: #86909c;
          margin-bottom: 5px;
        }
      }
    }
  }

  .table-head {
    margin: 20px 0 10px 0;

    :deep(.el-col) {
      padding: 10px;
      background-color: #f2f6fc;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  .table-list {
    .goods {
      margin-bottom: 10px;
      border: 1px solid #e1e6ed;
      border-right: none;

      :deep(.el-row) {
        font-size: 14px;
        line-height: 20px;

        .el-col {
          padding: 10px;
          border-right: 1px solid #e1e6ed;
        }
      }

      .image {
        width: 80px;
        height: 80px;
        border-radius: 4px;
        background-color: gray;
        margin-right: 18px;
      }

      .remark {
        font-size: 14px;
        line-height: 20px;
        border-top: 1px solid #e1e6ed;
        border-right: 1px solid #e1e6ed;
        padding: 8px 20px;
        display: flex;
        align-items: center;

        .label {
          width: 50px;
        }
      }
    }
  }

  .action-wrap {
    position: absolute;
    height: 64px;
    right: 0;
    left: 0;
    bottom: 0;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-right: 20px;
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
    background-color: white;
    z-index: 2;

    p {
      color: #86909c;
      margin-right: 20px;
    }
  }
}
</style>
